package com.yunkeji.common.filter.wrapper;

import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yunkeji.common.constant.Constants;
import com.yunkeji.common.exception.ServiceException;
import com.yunkeji.common.filter.CryptoFilter;
import com.yunkeji.common.utils.EncryptUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * 解密请求参数工具类
 *
 * @author wdhcr
 */
@Slf4j
public class DecryptRequestBodyWrapper extends HttpServletRequestWrapper {

    private final byte[] body;

    /**
     * RAS + AES
     *
     * @param request
     * @param privateKey
     * @param headerFlag
     * @throws IOException
     */
    public DecryptRequestBodyWrapper(
            HttpServletRequest request, String privateKey, String headerFlag) throws IOException {
        super(request);
        // 获取 AES 密码 采用 RSA 加密
        String headerRsa = request.getHeader(headerFlag);
        String decryptAes = EncryptUtils.decryptByRsa(headerRsa, privateKey);
        // 解密 AES 密码
        String aesPassword = EncryptUtils.decryptByBase64(decryptAes);
        request.setCharacterEncoding(Constants.UTF8);
        byte[] readBytes = IoUtil.readBytes(request.getInputStream(), false);
        String requestBody = new String(readBytes, StandardCharsets.UTF_8);
        // 解密 body 采用 AES 加密
        String decryptBody = EncryptUtils.decryptByAes(requestBody, aesPassword);
        log.info("请求原始内容=>{}", decryptBody);
        body = decryptBody.getBytes(StandardCharsets.UTF_8);
    }

    /**
     * 只需要RSA加密
     *
     * @param request
     * @throws IOException
     */
    public DecryptRequestBodyWrapper(
            HttpServletRequest request, CryptoFilter.CryptoConfig cryptoConfig, Long nonceHeader)
            throws IOException {
        super(request);
        byte[] readBytes = IoUtil.readBytes(request.getInputStream(), false);
        String requestBody = new String(readBytes, StandardCharsets.UTF_8);
        String decryptAes = EncryptUtils.decryptByRsa(requestBody, cryptoConfig.getPrivateKey());
        log.info("请求原始内容=>{}", decryptAes);
        JSONObject parse = JSONUtil.parseObj(decryptAes);
        Long nonceBody = parse.getLong("nonce");
        if (!nonceHeader.equals(nonceBody)) {
            throw new ServiceException("时间戳异常");
        }
        body = decryptAes.getBytes(StandardCharsets.UTF_8);
    }

    @Override
    public BufferedReader getReader() {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public int getContentLength() {
        return body.length;
    }

    @Override
    public long getContentLengthLong() {
        return body.length;
    }

    @Override
    public String getContentType() {
        return MediaType.APPLICATION_JSON_VALUE;
    }

    @Override
    public ServletInputStream getInputStream() {
        final ByteArrayInputStream bais = new ByteArrayInputStream(body);
        return new ServletInputStream() {
            @Override
            public int read() {
                return bais.read();
            }

            @Override
            public int available() {
                return body.length;
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {}
        };
    }
}
